/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:42
 */

package com.lenovo.mso2o.service;

import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.lenovo.framework.entity.FGson;
import com.lenovo.framework.rx.RxBus;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FPreferenceManager;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.biz.AccountManagerImpl;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.conf.MessageType;
import com.lenovo.mso2o.entity.g.Notification;
import com.lenovo.mso2o.entity.g.NotificationDao;
import com.lenovo.mso2o.ui.LoginActivity;
import com.lenovo.mso2o.ui.MainActivity;
import com.lenovo.mso2o.util.SendNotification;

import java.util.Date;


public class GetuiPushReceiver extends BroadcastReceiver {

    public static final String NEW_NOTIFICATION = "Refresh_Adapter";

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        DLog.d("GetuiSdkDemo", "onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                if(!AccountManagerImpl.instance.isLogin()){
                    return;
                }
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");

                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
                DLog.d("第三方回执接口调用", (result ? "成功" : "失败"));
                DLog.d(getClass().getName(), bundle.toString());

                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");

                if (payload != null) {
                    String data = new String(payload);

                    DLog.d("GetuiSdkDemo", "receiver payload : " + data);

                    try {
                        final Notification notification = FGson.gson().fromJson(data, new TypeToken<Notification>() {
                        }.getType());
                        if (notification.getType() == null) {
                            break;
                        }
                        if (MessageType.LOGOUT.getValue() == notification.getType()) {
                            if (AccountManagerImpl.instance.isLogin()) {
                                Toast.makeText(context, R.string.conflict_login, Toast.LENGTH_LONG).show();
                                AccountManagerImpl.instance.logout();
                                intent = new Intent(context, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            }
                            return;
                        } else {
                            if(null != notification.getDesc() && !"".equals(notification.getDesc().trim())) {
                                NotificationDao dao = MSApplication.getDaoSession().getNotificationDao();
                                notification.setDate(new Date());
                                dao.insert(notification);
                                RxBus rxBus = MSApplication.getRxBus();
                                rxBus.send(NEW_NOTIFICATION);
                            }
                            if (MessageType.GRAB_NOTIFY.getValue() == notification.getType()) {
                                SendNotification.sendNotification(R.drawable.ic_launcher, notification.getTitle(), notification.getDesc(), context, true, notification.getType(), PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_GRAB);
                            } else if (MessageType.RECEIVE_NOTIFY.getValue() == notification.getType()) {
                                SendNotification.sendNotification(R.drawable.ic_launcher, notification.getTitle(), notification.getDesc(), context, true, notification.getType(), PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_RECEIVING);
                            } else if (MessageType.SLA_NOTIFY.getValue() == notification.getType()) {
                                SendNotification.sendNotification(R.drawable.ic_launcher, notification.getTitle(), notification.getDesc(), context, true, notification.getId().intValue(), PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_FILTER);
                            } else if (MessageType.BILL_NUMBER.getValue() == notification.getType()) {
                            }
                        }
                    }catch(Exception e){
                        DLog.p(e);
                    }
                }

                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                final String cid = bundle.getString("clientid");
                DLog.d("cid:", cid);
                if(TextUtils.isEmpty(FPreferenceManager.getString(MSConstants.KEY_GETUI_CID, ""))) {
                    FPreferenceManager.putString(MSConstants.KEY_GETUI_CID, cid);
                }
                break;

            case PushConsts.THIRDPART_FEEDBACK:
                /*
                 * String appid = bundle.getString("appid"); String taskid =
                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
                 * String result = bundle.getString("result"); long timestamp =
                 * bundle.getLong("timestamp");
                 * 
                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid = " +
                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d("GetuiSdkDemo",
                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
                 */
                break;

            default:
                break;
        }
    }
}
